import 'package:flutter/material.dart';
import 'package:flutter_draggable_gridview/flutter_draggable_gridview.dart';
import 'package:get/get.dart';
import 'package:ball_lion/module/home/home_channel_filter_logic.dart';
import 'package:ball_lion/entity/home/news_classfier_entity.dart';
import 'package:ball_lion/utils/widget_utils.dart';
import 'package:ball_lion/widgets/base/wqs_dialog.dart';
import 'package:ball_lion/resources/colours.dart';
import 'package:ball_lion/utils/utils.dart';
import 'package:ball_lion/widgets/base/wqs_text.dart';

class HomeChannelFilterPage extends StatefulWidget {
  const HomeChannelFilterPage({super.key});

  @override
  State<HomeChannelFilterPage> createState() => _HomeChannelFilterPageState();
}

class _HomeChannelFilterPageState extends State<HomeChannelFilterPage> {
  final HomeChannelFilterLogic logic = Get.put(HomeChannelFilterLogic());
  final double itemwidth = (Get.width - 32 - 20) / 3;
  final double itemheight = 32;
  @override
  Widget build(BuildContext context) {
    return GetBuilder<HomeChannelFilterLogic>(builder: (logic) {
      return Scaffold(
        appBar: AppBar(
          title: QsText('全部频道'),
          leading: Align(
            alignment: Alignment.center,
            child: Image.asset(Utils.getImgPath("bottomsheet_close.png"),
                    width: 24, height: 24)
                .tap(
              () async {
                if (logic.editable) {
                  bool? result = await Get.dialog(QsDialog.alert(
                      "您的编辑未完成，是否保存后退出",
                      confirmText: "是",
                      cancelText: "否"));
                  if (result == true) await logic.updateMyChannels();
                  Get.back();
                } else {
                  Get.back();
                }
              },
            ),
          ),
          actions: [
            Container(
              padding: const EdgeInsets.only(right: 16),
              alignment: Alignment.center,
              child: QsText(
                logic.editable ? "完成" : "编辑",
                color: logic.editable ? Colours.main : Colours.text,
                fontWeight: FontWeight.w500,
              ).tap(
                () {
                  logic.clickEdit();
                },
              ),
            ),
          ],
        ),
        body: Column(
          children: [
            const Divider(color: Colours.greyEE, height: 0.5),
            _selectedChannels(),
            const SizedBox(height: 10),
            Expanded(child: otherChannels())
            // Expanded(child: _contentList())
          ],
        ),
      );
    });
  }

  Widget _selectedChannels() {
    final ratio = itemwidth / itemheight;
    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      margin: const EdgeInsets.only(top: 16),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          Row(
            textBaseline: TextBaseline.alphabetic,
            crossAxisAlignment: CrossAxisAlignment.baseline,
            children: [
              QsText(
                "我的频道",
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
              const SizedBox(width: 12),
              QsText(logic.editable ? "长按拖动排序" : "点击进入频道",
                  color: Colours.grey99, fontSize: 12),
            ],
          ),
          const SizedBox(height: 12),
          logic.myChannels.isEmpty
              ? Container()
              : DraggableGridViewBuilder(
                  shrinkWrap: true,
                  isOnlyLongPress: false,
                  gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                      crossAxisCount: 3,
                      childAspectRatio: ratio,
                      mainAxisSpacing: 12,
                      crossAxisSpacing: 13),
                  children: logic.myChannels
                      .map((e) => DraggableGridItem(
                          child: item(e), isDraggable: e.fixed != 1))
                      .toList(),
                  dragCompletion: (list, beforeIndex, afterIndex) {
                    final item = logic.myChannels.removeAt(beforeIndex);
                    logic.myChannels.insert(afterIndex, item);
                    update();
                  },
                ),
        ],
      ),
    );
  }

  Widget otherChannels() {
    final ratio = itemwidth / itemheight;

    return Container(
      padding: const EdgeInsets.symmetric(horizontal: 16),
      color: Colors.white,
      child: Column(
        crossAxisAlignment: CrossAxisAlignment.start,
        children: [
          const Row(
            textBaseline: TextBaseline.alphabetic,
            crossAxisAlignment: CrossAxisAlignment.baseline,
            children: [
              QsText(
                "其他频道",
                fontSize: 16,
                fontWeight: FontWeight.w500,
              ),
              SizedBox(width: 12),
              QsText(
                '点击添加频道',
                color: Colours.grey99,
                fontSize: 12,
              )
            ],
          ).marginSymmetric(horizontal: 0),
          const SizedBox(height: 12),
          logic.otherChannels.isNotEmpty
              ? Expanded(
                  child: GridView.builder(
                    shrinkWrap: false,
                    gridDelegate: SliverGridDelegateWithFixedCrossAxisCount(
                        crossAxisCount: 3,
                        childAspectRatio: ratio,
                        mainAxisSpacing: 12,
                        crossAxisSpacing: 13),
                    itemBuilder: (context, index) {
                      return item(logic.otherChannels[index]);
                    },
                    itemCount: logic.otherChannels.length,
                  ),
                )
              : Container(
                  height: 100,
                  alignment: Alignment.center,
                  child: QsText(
                    "已全部添加到“我的频道”",
                    color: Colours.grey66,
                  ),
                ),
        ],
      ),
    );
  }

  Widget item(NewsClassfierEntity data) {
    //其他频道
    bool isOther = logic.otherChannels.any((element) => element.id == data.id);
    return GestureDetector(
      key: ValueKey(data.id),
      onTap: () {
        if (isOther) {
          if (logic.editable) {
            logic.otherChannels.remove(data);
            logic.myChannels.add(data);
            update();
            logic.updateMyChannels();
          }
        } else {
          if (logic.editable) {
            if (data.fixed == 1) return;
            logic.otherChannels.add(data);
            logic.myChannels.remove(data);
            update();
          } else {
            Get.back<String?>(result: data.id);
          }
        }
      },
      onLongPress: logic.editable ? null : () => logic.editable = true,
      behavior: HitTestBehavior.opaque,
      child: SizedBox(
        height: itemheight,
        width: itemwidth,
        child: Stack(
          children: [
            Container(
              height: itemheight,
              width: itemwidth,
              alignment: Alignment.center,
              decoration: BoxDecoration(
                  borderRadius: BorderRadius.circular(4),
                  color: Colours.greyF5F7FA),
              child: QsText(
                data.name ?? '',
                maxLines: 1,
              ),
            ),
            if (logic.editable && data.fixed != 1)
              Positioned(
                top: 2,
                right: 2,
                child: Image.asset(
                  width: 12,
                  Utils.getImgPath(
                      isOther ? "add_small.png" : "close_36_round.png"),
                ),
              ),
          ],
        ),
      ),
    );
  }
}
